/*
 * Copyright (c) 2020. bmy
 */

const gulp = require('gulp');
const exec = require('child_process').exec;
const file = require('./test');
var oldText = [], newText = [];


/**
 * 执行 vue-cli-service route 命令进行路由编译
 */
gulp.task('AutoCompileRouter', function (cb) {
  return exec('npm run route', (err, stdout, stderr) => {
    if (err) {
      console.log("编译失败: ", err);
      cb(err)
    } else {
      console.log("编译成功");
    }
  });
});

gulp.task('AutoAddUrl', async (cb) => {
  newText = await file.getFileList();
  console.log("newText ------------- ", newText)
  let cy = diff(newText, oldText);
  console.log("diff ------------- ", cy)
  oldText = newText;
  cb()
})

/**
 * 监听 page 所有文件的修改，自动触发 AutoCompileRouter 任务
 */
gulp.task('auto', async () => {
  oldText = await file.getFileList();
  console.log("oldText ------------- ", oldText)
  // gulp.watch('src/application/page/**/*', gulp.parallel('AutoCompileRouter'));
  gulp.watch('src/core/config/configure.config.ts', gulp.parallel('AutoAddUrl'));
});

/**
 * diff 对比文件修改前后的差异，取出差异和结果
 * @param {*} newV 修改后
 * @param {*} oldV 修改前
 * @returns 
 */
function diff(newV, oldV) {
  let status = "";

  let oV = null, nV = null;
  if (newV.length > oldV.length) {
    status = "add"
    oV = new Set(newV)
    nV = new Set(oldV)
  } else {
    status = "delete"
    oV = new Set(oldV);
    nV = new Set(newV);
  }

  return {
    status,
    item: Array.from(new Set([...oV].filter(x => !nV.has(x))))
  }
}

gulp.task('default', gulp.parallel('auto'));